from fastapi import APIRouter, Depends, Request
from module_admin.service.login_service import LoginService
from module_admin.entity.vo.employee_vo import EmployeeModel,EmployeeQueryModel
from typing import List
# 权限
from module_admin.aspect.interface_auth import CheckUserInterfaceAuth
from sqlalchemy.ext.asyncio import AsyncSession
from config.get_db import get_db
from module_admin.aspect.data_scope import GetDataScope
from module_admin.service.employee_service import EmployeeService
from utils.log_util import logger
from utils.response_util import ResponseUtil
from pydantic_validation_decorator import ValidateFields
from module_admin.annotation.log_annotation import Log
from config.enums import BusinessType
from datetime import datetime


# 用户管理 -路由-实现
employeeController = APIRouter(prefix='/system/employee', dependencies=[Depends(LoginService.get_current_user)])

# 功能1：获取员工信息列表
    # 这是 FastAPI 的路由装饰器，定义了一个 GET 请求的 /list 接口；
    # response_model 指定了接口返回的数据格式。这里表示返回的是一个 EmployeeModel 类型的列表（List），即多个员工对象。
    # 接口有一个依赖项，只有拥有 system:employee:list 权限的用户才能访问
@employeeController.get(
    '/list', response_model=List[EmployeeModel], dependencies=[Depends(CheckUserInterfaceAuth('system:employee:list'))]
)
# 员工查询模型，使用 Depends 依赖注入系统自动处理查询参数；
# EmployeeQueryModel.as_query 来自module_admin/annotation/pydantic_annotation.py；这个装饰器的主要作用是将 Pydantic 模型转换为 FastAPI 的查询参数；
async def get_system_employee_list(
    request: Request,
    employee_query: EmployeeQueryModel = Depends(EmployeeQueryModel.as_query), # 将 Pydantic 模型转换为 FastAPI 的查询参数；
    query_db: AsyncSession = Depends(get_db), # 数据库连接
    data_scope_sql: str = Depends(GetDataScope('EmployeeInfo')), # 获取当前用户数据权限对应的查询sql语句
):
    employee_query_result = await EmployeeService.get_employee_list_services(query_db, employee_query, data_scope_sql, is_page=True)
    logger.info('获取成功')

    return ResponseUtil.success(model_content=employee_query_result)

# 功能2-1：新增表单，校验姓名 => 查询不重复返回True
@employeeController.get('/checkNameUnique', dependencies=[Depends(CheckUserInterfaceAuth('system:employee:add'))])
async def check_employee_name_unique(name: str, query_db: AsyncSession = Depends(get_db)):
    from sqlalchemy import select
    from module_admin.entity.do.employee_do import EmployeeInfo
    result = await query_db.execute(select(EmployeeInfo).where(EmployeeInfo.name == name, EmployeeInfo.del_flag == '0'))
    exists = result.scalar() is not None
    return {"unique": not exists}

# 功能2-2：新增员工  POST /system/employee
# 数据验证装饰器：
    # 当请求到达 add_system_dept 接口时，装饰器会先执行
    # 它会根据 'add_dept' 这个验证模型来检查请求中的 DeptModel 数据是否符合要求  @NotBlank
    # 如果数据验证失败，会直接返回错误响应；
    # 只有验证通过后，才会执行实际的接口处理逻辑
@employeeController.post('',  dependencies=[Depends(CheckUserInterfaceAuth('system:employee:add'))])
@ValidateFields(validate_model='employee')
@Log(title='员工管理', business_type=BusinessType.INSERT)
async def add_system_employee(
    request: Request,
    employee: EmployeeModel,
    query_db: AsyncSession = Depends(get_db),
    current_user=Depends(LoginService.get_current_user)
):
    # 自动填充创建人和时间 
    employee.create_by = current_user.user.user_name
    employee.create_time = datetime.now()
    employee.update_by = current_user.user.user_name
    employee.update_time = datetime.now()
    # 业务逻辑
    result = await EmployeeService.add_employee_services(query_db, employee)
    return ResponseUtil.success(msg='新增成功', data=result)
